package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.ContractDto;
import com.ant.storage.excel.ContractExcel;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.StorageContractMapper;
import com.ant.storage.pojo.PurchaserRecordImg;
import com.ant.storage.pojo.StorageContract;
import com.ant.storage.pojo.StoragePayment;
import com.ant.storage.pojo.UserInfo;
import com.ant.storage.service.IPurchaserRecordImgService;
import com.ant.storage.service.IStorageContractService;
import com.ant.storage.service.IStoragePaymentService;
import com.ant.storage.utils.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author melon
 * @since 2024-05-08
 */
@Service
public class StorageContractServiceImpl extends ServiceImpl<StorageContractMapper, StorageContract> implements IStorageContractService {

    @Autowired
    public IPurchaserRecordImgService imgService;

    @Autowired
    public IStoragePaymentService paymentService;


    @Autowired
    public ServletContext servletContext;

    @Override
    public PageInfo<StorageContract> queryList(ContractDto dto) {
        try {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<StorageContract> wrapper = new QueryWrapper<>();
            if (dto.getCityId() != null) {
                wrapper.lambda().eq(StorageContract::getCityId, dto.getCityId());
            }
            if (dto.getCompanyId() != null) {
                wrapper.lambda().eq(StorageContract::getCompanyId, dto.getCompanyId());
            }
            if (StringUtils.isNotEmpty(dto.getContractName())) {
                wrapper.lambda().like(StorageContract::getContractName, dto.getContractName());
            }
            if (StringUtils.isNotEmpty(dto.getContractNumber())) {
                wrapper.lambda().like(StorageContract::getContractNumber, dto.getContractNumber());
            }
            if (StringUtils.isNotEmpty(dto.getContractTrademark())) {
                wrapper.lambda().like(StorageContract::getContractTrademark, dto.getContractTrademark());
            }

            if (dto.getIsRecycle() != null) {
                wrapper.lambda().eq(StorageContract::getIsRecycle, dto.getIsRecycle());
            }
            if (StringUtils.isNotEmpty(dto.getContractName())) {
                wrapper.lambda().eq(StorageContract::getContractName, dto.getContractName());
            }

            if (dto.getCollectionDate() != null && dto.getCollectionDate().size() > 0) {
                wrapper.lambda().between(StorageContract::getCollectionDate,
                        dto.getCollectionDate().get(0) + " 00:00:00",
                        dto.getCollectionDate().get(1) + " 23:59:59");
            }

            if (userInfo.getRoles() != null && userInfo.getRoles().equals("admin")) {
                wrapper.lambda().eq(StorageContract::getCityId, userInfo.getCityId());
            }
            wrapper.orderByDesc("id");
            List<StorageContract> list = this.baseMapper.selectList(wrapper);
            list.stream().forEach(item -> {
                if (item.getAnnex() != null) {
                    List<PurchaserRecordImg> imgList = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                            .in("id", item.getAnnex().split(",")));
                    if (imgList != null && imgList.size() ==1) {
                        item.setAnnex(imgList.get(0).getUrl());
                    }else{
                        item.setAnnexList(imgList);
                    }

                }
            });
            PageInfo<StorageContract> pageInfo = new PageInfo<>(list);
            return pageInfo;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }

    @Override
    public StorageContract findContractById(Integer id) {
        if (id == null) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), "参数错误");
        } else {
            StorageContract one = this.baseMapper.selectOne(new QueryWrapper<StorageContract>()
                    .eq("id", id));
            if (one.getAnnex() != null) {
                List<PurchaserRecordImg> imgList = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                        .in("id", one.getAnnex().split(",")));
                one.setAnnexList(imgList);
            }
            if (one.getContractPdf() != null) {
                List<PurchaserRecordImg> img = imgService.list(new QueryWrapper<PurchaserRecordImg>()
                        .in("id", one.getContractPdf().split(",")));
                one.setContractPdfTUrl(img);
            }

            List<StoragePayment> list = paymentService.list(new QueryWrapper<StoragePayment>()
                        .eq("parent_id", one.getId()));
            if(list != null && list.size() > 0){
                one.setPaymentList(list);
            }
            return one;
        }
    }

    @Override
    public ResultVo contractSave(StorageContract dto) {
        synchronized (this) {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            if (dto.getId() == null) {
                dto.setCityId(userInfo.getCityId());
                dto.setCompanyId(userInfo.getDepId());
                dto.setCreatorBy(userInfo.getNameId().toString());
                dto.setCreationTime(new Date());
                this.baseMapper.insert(dto);
            } else {
                this.baseMapper.updateById(dto);
            }

            return ResultVo.success("操作成功");
        }
    }

    @Override
    public ResultVo contractUpdate(StorageContract dto) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        dto.setContractNumber("HT" + RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
        dto.setCreationTime(new Date());
        this.baseMapper.updateById(dto);
        return ResultVo.success("操作成功");
    }

    @Override
    public List<ContractExcel> exportCensus(Integer isRecycle) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        List<ContractExcel> list = this.baseMapper.exportCensus(isRecycle, userInfo.getCityId());
        list.stream().forEach(item -> {
            item.setIsRecycle(item.getIsRecycle().equals("0") ? "正常" : "到期");
        });
        return list;
    }

    @Override
    public ResultVo uploadCommodity(MultipartFile file) {
        StorageContract management;//定义员工POJO类
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        //解析出来的封装好要返回的对象
        List<StorageContract> list = new ArrayList<>();
        //插入数据库时，需要日期格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
        if (file.isEmpty()) {
            // 先判断客户端上传的excel有没有效
            throw new RuntimeException("文件错误");
        }
        try {
            //获得上传的excel文件
            //HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            //获取第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取行数
            int rowNums = sheet.getPhysicalNumberOfRows();
            //遍历行数
            for (int i = 1; i < rowNums; i++) {
                management = new StorageContract();
                //得到该行的数据
                XSSFRow row = sheet.getRow(i);
                if (row != null) {
                    //获得该行的单元格数量，并遍历出单元格
                    int cellNums = row.getPhysicalNumberOfCells();
                    for (int j = 0; j < cellNums; j++) {
                        XSSFCell cell = row.getCell(j);
                        cell.setCellType(CellType.STRING);
                        if (cell != null) {
                            //开始填装Emp实体属性
                            String value = cell.getStringCellValue();
                            if (value == null) {
                                value = "";//如果值是空的则空字符串
                            }
                            management.setCityId(1);
                            management.setCompanyId (1);
                            // commodity.setCommodityBarCode(commodityMapper.selectLastID());
                            //每一个字段对应的index
                            switch (j) {
                                case 0:
                                    management.setContractNumber(value);
                                    break;
                                case 1:
                                    management.setUsageTime(value);
                                    break;
                                case 2:
                                    management.setSquareMetre(value);
                                    break;
                                case 3:
                                    management.setContractName(value);
                                    break;
                                case 4:
                                    management.setContractTrademark(value);
                                    break;
                                case 5:
                                    management.setUnitName(value);
                                    break;
                                case 6:
                                    management.setContacts(value);
                                    break;
                                case 7:
                                    management.setTelephone(value);
                                    break;
                                case 8:
                                    management.setAmount(value);
                                    break;
                                case 9:
                                    management.setNumbers(Integer.parseInt(value));
                                    break;
                                case 10:
                                    management.setHandle(value);
                                    break;
                                case 11:
                                    management.setSubjects(value);
                                    break;
                                case 12:
                                    management.setContractTime(value);
                                    break;
                                case 13:
                                    management.setIsRecycle(Integer.parseInt(value));
                                    break;
                                case 14:
                                    management.setCollectionDate(value);
                                    break;
                                case 15:
                                    management.setNotes(value);
                                    break;
                            }
                            management.setCreatorBy(userInfo.getNameId().toString());
                            management.setCreationTime(new Date());
                        }
                    }
                    //一个完整emp
                    this.baseMapper.insert(management);
                }
            }
            return ResultVo.success("上传成功");

        } catch (Exception e) {
            e.printStackTrace();
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }
}
